package com.servlet;

import com.entry.Book;
import com.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * --- Be Humble and Hungry ---
 *
 * @author McMeloxD
 * @date 2024/6/27
 * @desc
 */
@WebServlet("/addBook")
public class AddBookServlet extends HttpServlet {
    private UserServiceImpl userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 0 设置编码格式
        // req.setCharacterEncoding("utf-8");
        // resp.setContentType("text/html;charset=utf-8");

        // 1接收请求数据
        String name = req.getParameter("bname");
        float price = Float.parseFloat(req.getParameter("price"));
        String press = req.getParameter("press");
        String author = req.getParameter("author");
        int number = Integer.parseInt(req.getParameter("number"));
        Book book = new Book(name, price, press, author, number);
        System.out.println(book);
        // 2将数据传递给业务层
        List<Book> books = userService.addBook(book);
        books.forEach(x -> System.out.println(x));
        if (books.size() > 0) {
            //如果返回有数据，交给页面
            req.setAttribute("books", books);
            req.getRequestDispatcher("BookList.jsp").forward(req, resp);
        }else {
            //没有数据，弹出提醒,在页面控制跳转
            req.setAttribute("msg", "这本书已经在书库了哦~");
        }

        // 3做出响应

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
